﻿var isFileRequest = false;
function setupAjax() {
    // 请求前先设置好antitoken
    $.ajaxSetup({
        beforeSend: function (xhr) {
            xhr.setRequestHeader("RequestVerificationToken",
                $('input:hidden[name="__RequestVerificationToken"]').val());
            if (!isFileRequest) {
                xhr.setRequestHeader("Content-Type", "application/json");
            }
        }
    });
}

setupAjax();

var errTimeOut;
$(function () {
    //setDefaultConnectInfo(0);
    Config.load(1, '.main-config', o => setCurrentDbType(o.DbType, true), () => setDefaultConnectInfo(0));

    $('#btnGenerate').on('click', function () {
        var data = $.serializeObj('.main-config');
        console.log(data);
        $.post("/?handler=generate", JSON.stringify(data), res => {
            //console.log(res);
            if (res.code === 0 || res.code === "Success") {
                var content = '';
                var dcontent = '<div class="item"><div class="oper">';
                $.each(res.data,
                    (index, item) => {
                        content += '<div class="item">';
                        content +=
                            '<div class="oper"><a class="copy" data-toggle="tooltip" title="代码已复制" href="javascript:;" data-clipboard-action="copy" data-clipboard-text="' +
                            item.sourceContent +
                            '">Copy</a><a class="download" title="点击下载代码文件" href="/?handler=Download&fileName=' +
                            item.fileLink +
                            '" target="_blank">Download</a></div>';
                        content += '<div class="content">' + item.htmlContent + '</div>';
                        content += '</div>';
                        dcontent +=
                            '<a class="download" title="点击下载代码文件" href="/?handler=Download&fileName=' +
                            item.fileLink +
                            '" target="_blank">' +
                            item.fileLink +
                            '</a>';
                    });
                dcontent += '</div></div>'; // end item
                content = dcontent + content;
                $('#result').html(content);
                var clipboard = new ClipboardJS('.copy');
                clipboard.on('success',
                    function (e) {
                        console.info('Action:', e.action);
                        //console.info('Text:', e.text);
                        //console.info('Trigger:', e.trigger);
                        e.clearSelection();
                        $(this).tooltip();
                    });
                clipboard.on('error',
                    function (e) {
                        console.error('Action:', e.action);
                        console.error('Trigger:', e.trigger);
                    });
                saveCache();
            } else {
                $("#btnGenerate").attr("data-content", res.message);
                $("[data-toggle='popover']").popover('hide');
                $("[data-toggle='popover']").popover('show');
                $("#result").html("");
                clearTimeout(errTimeOut);
                errTimeOut = setTimeout(() => {
                    $("[data-toggle='popover']").popover('hide');
                }, 5000);
            }
        });
    });

    $("select[name=DbType]").on('change', e => {
        var that = $(e.target);
        setCurrentDbType(parseInt(that.val()));
    });

    $("select[name=TemplateFileName]").on('change', e => {
        var that = $(e.target);
        var opt = that.find('option:selected');
        $("input[name=TemplateName").val(opt.text());
        $("input[name=LanguageDataType").val(opt.attr('data-type'));
    });

    $("#btnShowUpload").click(e => {
        showUpload('模板上传', res => console.log("上传成功"));
    });

    setDefaultTemplateName();

    // 设置当前数据库类型
    var type = $("select[name=DbType]").val();
    setCurrentDbType(parseInt(type));
});

// 设置默认模板名
function setDefaultTemplateName() {
    var opt = $("select[name=TemplateFileName]").find('option:selected');
    $("input[name=TemplateName").val(opt.text());
    $("input[name=LanguageDataType").val(opt.attr('data-type'));
}

function setCurrentDbType(type, onlySet) {
    $.post('/?handler=changedbtype&dbType=' + type, {}, res => {
        if (onlySet) {
            return;
        }
        if (res.code === "Success") {
            setDefaultConnectInfo(type, res.data);
        } else {
            setDefaultConnectInfo(type);
        }
    });
}

function saveCache() {
    Config.save(1, '.main-config', o => Config.dbTypes[o.DbType] + '|' + o.ServerName + '|' + o.Port + '|' + o.Database);
}

function setDefaultConnectInfo(dbType, data) {
    var isDefault = data === undefined;
    switch (dbType) {
        case 0: // sqlserver
            setValue('Database', isDefault ? 'LanGuo' : data.database);
            setValue('Namespace', isDefault ? 'FDSimpleModelGenerator.Demo.SqlServer' : data.namespace);
            setValue('UserId', isDefault ? 'sa' : data.userId);
            setValue('Password', isDefault ? 'DX.net123!@#' : data.password);
            setValue('ServerName', isDefault ? 'test-db.xianshuabao.com' : data.serverName);
            setValue('TableName', isDefault ? 'romOrder' : data.tableName);
            setValue('Port', isDefault ? '1433' : data.port);
            break;
        case 1: // mysql
            setValue('Database', isDefault ? 'demo' : data.database);
            setValue('Namespace', isDefault ? 'FDSimpleModelGenerator.Demo.MySql' : data.namespace);
            setValue('UserId', isDefault ? 'root' : data.userId);
            setValue('Password', isDefault ? '1234' : data.password);
            setValue('ServerName', isDefault ? 'localhost' : data.serverName);
            setValue('TableName', isDefault ? 'user' : data.tableName);
            setValue('Port', isDefault ? '3306' : data.port);
            break;
        case 2: // sqlite
            setValue('Database', isDefault ? '忽略' : data.database);
            setValue('Namespace', isDefault ? 'FDSimpleModelGenerator.Demo.Sqlite' : data.namespace);
            setValue('UserId', isDefault ? '忽略' : data.userId);
            setValue('Password', isDefault ? '忽略' : data.password);
            setValue('ServerName', isDefault ? 'D:\\DB\\sqlite\\demo.db' : data.serverName);
            setValue('TableName', isDefault ? 'person' : data.tableName);
            setValue('Port', isDefault ? '0' : data.port);
            break;
        case 3: // postgreSQL
            setValue('Database', isDefault ? 'demodb' : data.database);
            setValue('Namespace', isDefault ? 'FDSimpleModelGenerator.Demo.PostgreSQL' : data.namespace);
            setValue('UserId', isDefault ? 'postgres' : data.userId);
            setValue('Password', isDefault ? '1234' : data.password);
            setValue('ServerName', isDefault ? 'localhost' : data.serverName);
            setValue('TableName', isDefault ? 'user' : data.tableName);
            setValue('Port', isDefault ? '5432' : data.port);
            break;
        default:
            setValue('Database', '');
            setValue('Namespace', 'FDSimpleModelGenerator.Demo.Default');
            setValue('UserId', '');
            setValue('Password', '');
            setValue('ServerName', '');
            setValue('TableName', '');
            break;
    }
}

// type:0 input 1:select
// name: 对应名称，value:对应值
function setValue(name, value, type = 0) {
    var sType = type === 0 ? 'input' : 'select';
    name = sType + "[name=" + name + "]";
    $(name).val(value);
}
